<?php 
namespace app\Index\controller;
use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;
use app\index\model\User;
class Login extends Controller
{
    public function login(){
        if(Request::instance()->isPost()){
            $admin = new User();
            $data = input('post.');//接收POST数据
            $username = strtolower(trim($data['uname']));
            $password = md5($data['password']);
            $autologin = isset($data['islogin'])?1:0;//自动登录设置
            $captcha = $data['code'];//验证码
            if(empty($username) || empty($password)){
                return json(array("status"=>0,"msg"=>"用户名和密码不能为空！"));
            }
            if(!captcha_check($captcha)){
                return json(array("status"=>0,"msg"=>"验证码错误，请重新输入！"));
            };

            $userinfo = $admin -> login($username,$password);//后台密码验证

            if($userinfo['status'] == 0){
                return json(array("status"=>0,"msg"=>"对不起，您的账号已被冻结，请联系系统管理员！"));
            }

            if(!empty($userinfo)){
                if($userinfo['upass'] == $password){
                    Session::set('user_id',$userinfo['uid']);
                    Session::set('user_name',$userinfo['uname']);
                    Session::set('user_nik',$userinfo['unik']);
                    Session::set('user_role',$userinfo['urole']);
                    Session::set('last_time',time()+1800);
                    if ($autologin) {
                        Cookie::set('user_id', encry_code($userinfo['uid']), 604800);
                        Cookie::set('user_name', encry_code($userinfo['uname']), 604800);
                        Cookie::set('user_psk', encry_code($userinfo['upass']), 604800);
                    }
                    return json(array("status"=>1,"msg"=>"登录成功"));//$this -> success('登录成功，正在为您跳转','index/index');
                }else{
                    return json(array("status"=>2,"msg"=>"登录失败，用户名或密码不正确！"));
                }
            }else{
                return json(array("status"=>2,"msg"=>"用户不存在，请查证后再试..."));
            }
        }
        return $this -> fetch('login');
    }

    public function logout(){
        Session::clear();//退出清空Session
        //退出清空Cookie，Cookie::clear();无效，逐项销毁
        Cookie::set('user_id', null, 0);
        Cookie::set('user_name', null, 0);
        Cookie::set('user_psk', null, 0);
        return $this -> success('退出登录',url('Login/login'));//跳转到登录页面
    }
}